package org.wangduqing.ibatisdao.spring.rowMapper;

import java.math.BigDecimal;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.support.JdbcUtils;
import org.wangduqing.ibatisdao.util.CamelCaseUtils;

public class GenericRowMapper<T> implements RowMapper<T> {
	
	private Class<T> clazz;
	
	public GenericRowMapper(Class<T> claz){
		
		this.clazz = claz;
		
	}
	
	protected String getColumnKey(String columnName){
		
		return columnName;
		
	}
	
	protected Object getColumnValue(ResultSet rs, int index) throws SQLException{
		
		return JdbcUtils.getResultSetValue(rs, index);
		
	}

	@Override
	public T mapRow(ResultSet resultSet, int rowNum) throws SQLException {
		
		try {
			
			ResultSetMetaData rsmd = resultSet.getMetaData();
			int columnCount = rsmd.getColumnCount();
			T bean = clazz.newInstance();
			ConvertUtils.register(new org.wangduqing.ibatisdao.util.DateConverter(), Date.class);
			ConvertUtils.register(new org.wangduqing.ibatisdao.util.BigDecimalConverter(), BigDecimal.class);
			ConvertUtils.register(new org.wangduqing.ibatisdao.util.IntegerConverter(), Integer.class);
			for(int i=1; i<=columnCount; i++){
				
				String key = getColumnKey(JdbcUtils.lookupColumnName(rsmd, i));
				Object obj = getColumnValue(resultSet, i);
				String camelKey = CamelCaseUtils.toCamelCase(key);
				BeanUtils.setProperty(bean, camelKey, obj);
				
			}
			return bean;
			
		} catch (Exception e) {
			
			throw new SQLException("mapRow error.", e);
			
		}
		
	}

}
